package org.study;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerDemo {
    public static void main(String[] args) {
        try {
            // 创建一个 ServerSocket 在端口 8080 监听客户端连接
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(8080);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            System.out.println("服务器已启动，等待客户端连接...");

            // 使用 accept() 方法阻塞等待客户端连接
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端已连接");

            // 获取输入流，用于接收客户端发送的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            // 获取输出流，用于向客户端发送数据
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            String message;

            // 循环接收客户端消息，并将消息回传给客户端
            // in的readLine会读取socket流，在读取是会形成阻塞
            while ((message = in.readLine()) != null) {
                System.out.println("收到客户端的消息：" + message);
                out.println("服务器收到：" + message);
            }

            // 关闭连接
            clientSocket.close();
            serverSocket.close();

        } catch (IOException e) {
            System.out.println("服务器异常: " + e.getMessage());
        }
    }


}
